
/*
 * =====================================================================================
 *
 *       Filename:  HttpAck.cc
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  12/05/19 18:10:15
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  XXXXXXX (), XXXX@jd.com
 *        Company:  JDAI
 *        Copyright:  Copyright 2019, XXXXXXX
 *
 * =====================================================================================
 */
#include <sstream>
#include <string>

#include "HttpAck.h"

using std::string;
using std::stringstream;

void httpAck(RPCContextSPtr cxt, const int& err, const float& progress, const string& audioData, string timestamp) {
    //LOG(INFO) << "[req=" << cxt->mspHttpParam->mReqID << "][seq=" << cxt->mspHttpParam->mSeqID << "][err=" << err << "][len=" << audioData.length() << "]" << endl;
    cJSON* root = cJSON_CreateObject();
    butil::IOBuf audioBuf;
    char* jsonStr = NULL;
    cJSON_AddItemToObject(root, "status", cJSON_CreateNumber(err));
    cJSON_AddStringToObject(root, "message", get_err_msg(err));
    cJSON_AddStringToObject(root, "request_id", cxt->mspHttpParam->mReqID.c_str());
    cJSON_AddItemToObject(root, "index", cJSON_CreateNumber(cxt->mspHttpParam->mSeqID));

    if (err == OK) {
        cJSON_AddItemToObject(root, "progress", cJSON_CreateNumber(progress));
        cJSON_AddStringToObject(root, "audio", audioData.c_str());
    }

    if (timestamp.size() != 0) {
        cJSON_AddStringToObject(root, "timestamp", timestamp.c_str());
    }

    jsonStr = cJSON_PrintUnformatted(root);
    audioBuf.append(jsonStr);
    cxt->mpRpcCntl->http_response().set_content_type("application/json");
    cxt->mpRpcCntl->http_response().SetHeader("Request-Id", cxt->mspHttpParam->mReqID); //便于Nginx 进行过滤
    stringstream ss;
    string seqID;
    ss << cxt->mspHttpParam->mSeqID;
    ss >> seqID;
    cxt->mpRpcCntl->http_response().SetHeader("Sequence-Id", seqID);
    cxt->mpRpcCntl->response_attachment().swap(audioBuf);
    cxt->mpRpcDone->Run();

    if (jsonStr != NULL) {
        free(jsonStr);
    }

    if (root) {
        cJSON_Delete(root);
    }

    return;
}
